package com.mjk.common.tools.gson.adapter.impl;

import com.google.gson.TypeAdapter;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import com.google.gson.stream.JsonWriter;
import com.mjk.common.util.TimeUtils;

import java.io.IOException;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;

/**
 * localdatetime 序列化转换器
 */
public class LocalDateAdapterImpl extends TypeAdapter<LocalDate> {
    @Override
    public void write(JsonWriter jsonWriter, LocalDate localDateTime) throws IOException {
        jsonWriter.value(localDateTime.format(DateTimeFormatter.ofPattern(TimeUtils.DATE_FORMAT_DATEONLY)));
    }

    @Override
    public LocalDate read(JsonReader in) throws IOException {
        if (in.peek() == JsonToken.NULL) {
            return null;
        }
        return LocalDate.ofInstant(TimeUtils.parse(in.nextString()).toInstant(), ZoneId.systemDefault());
    }
}
